package tower.ai.base.chat.service;

import org.springframework.ai.chat.messages.*;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChatMessageHistoryService {

    private int maxSize = 20;


    @CachePut(value = "uid::", key = "#uid", cacheManager = "cacheManager")
    public List<String> addMessage(String uid, MessageType role, String lastMessage, @NonNull List<String> messages) {
        messages.add(role.getValue() + ":::" + lastMessage);
        if(messages.size() > maxSize){
            // 只保持到最大数量
            messages = new ArrayList<String>(messages.subList(messages.size() - maxSize, messages.size()));
        }
        return messages;
    }

    @Cacheable(value = "uid::", key = "#uid", cacheManager = "cacheManager")
    public List<String> getMessage(String uid) {
        return new ArrayList<String>();
    }

    public List<Message> buildMessage(List<String> messages) {
        List<Message> msg = new ArrayList<Message>(messages.size());
        for(String index : messages){
            String[] split = index.trim().split(":::");
            switch (split[0]){
                case "user":
                    msg.add(new UserMessage(split[1]));
                    break;
                case "assistant":
                    msg.add(new AssistantMessage(split[1]));
                    break;
                case "system":
                    msg.add(new SystemMessage(split[1]));
                    break;
                default:
                    break;
            }
        }
        return msg;
    }
}
